define([
  'views/List',
  'hbs!template/media/media-list'
], function(List, media_template){
  var MediaList = List.extend({
    template: media_template,

    flags: {
      dropBox: false // This flag will render a box where the user could drop files
    },

    initialize: function(options) {
      options || (options = {});
      View.prototype.initialize.call(this, options);

      if(options.flags) {
        this.flags = options.flags;
      }


      _.bindAll(this,
                'noopHandler',
                'dropHandler',
                'handleFiles');
      this.collection = new FileCollection();
      this.collection.bind("add", this.renderFilePreview, this);
      this.previews = [];
      this.cache = {};

    },

    initBox: function() {
      var dropBox = document.getElementById("dropbox");
      if(dropBox) {
        dropBox.addEventListener('dragenter', this.noopHandler, false);
        dropBox.addEventListener('dragexit', this.noopHandler, false);
        dropBox.addEventListener('dragover', this.noopHandler, false);
        dropBox.addEventListener('drop', this.dropHandler, false);
      }
    },

    noopHandler: function(evt){
      console.log("nooop");
      evt.stopPropagation();
      evt.preventDefault();
    },

    dropHandler: function(evt) {
      //console.log("Drop handler!");
      // Call noopHandler
      evt.stopPropagation();
      evt.preventDefault();

      // Reset old previews
      
      // Get files from dataTransfer object.
      console.log(evt.dataTransfer);
      var files = evt.dataTransfer.files;
      if(files) {
        var count = files.length;
        if(count) {
          this.handleFiles(files);
        }

      }
    },

    handleFiles: function(files) {
      //console.log("Handle Files.");
      var count = files.length,
      $label = $("#droplabel"),
      reader,
      file,
          i;
      for(i = 0; i < count; i++) {
        file = files[i];
        reader =  new FileReader();
        // Closure to have access to the file object when the filereader onload handler is called.
        //        reader.onload = this.handleReaderLoad;
        var self = this;
        reader.onload = (function(f){
          return function(evt) {
            var fileModel = new FileModel({
              file: f,
              content: evt.target.result,
              selected: true
            });
            self.collection.add(fileModel);
          };
        })(file);
        reader.readAsDataURL(file);
        this.renderFilesPreview();
      }
    },

    upload: function(callback) {
      console.log("upload");
      var i, files = this.getFiles();
      for(i=0; i < files.length; i++) {
        var f = files[i].get("file");
        if(f) {
          this.uploadFile(f, callback);
        }
      }
    },

    uploadFile: function(f, callback){
      console.log("UploadFile!!!");
      var that = this;
      var file = f || this.file;

      if(file) {
        // Create a form data
        var fd = new FormData();
        fd.append("data", file);

        // Create the XMLHttpRequest
        var xhr = new XMLHttpRequest();

        // Add events listeners
        /*   xhr.upload.addEventListener("progress", this.uploadProgress, false);
             xhr.addEventListener("load", this.uploadComplete, false);
             xhr.addEventListener("error", this.uploadFailed, false);
             xhr.addEventListener("abort", this.uploadCanceled, false);
        */
        // Send data
        xhr.open("POST", "/api/me/photos", true);
        xhr.onload = function() {
          if(xhr.status === 201) {
            var photo = $.parseJSON(xhr.responseText);
            callback(photo.id, photo.original.source);
          }
        };
        xhr.send(fd);
      }
    },

    serialize: function() {
      var data = this.collection.pagination;
      data._flags = this.flags;
      return data;
    }
  });

  return MediaList;
});